package Schema::Result::Model;

use strict;
use warnings;
use utf8;

use base qw/DBIx::Class::Core/;

__PACKAGE__->table('Model');
__PACKAGE__->add_columns( 
    Id => { data_type => 'integer', is_auto_increment => 1 },
    AggregateId => {},
    IdentityId  => {},
    IsAggregate  => {},
    Name  => {},
    Comment  => {},
);
__PACKAGE__->set_primary_key('Id');
__PACKAGE__->belongs_to(Aggregate => 'Schema::Result::Aggregate', 'AggregateId');
__PACKAGE__->belongs_to(Identity => 'Schema::Result::Identity', 'IdentityId');
__PACKAGE__->has_many(ModelProperties => 'Schema::Result::ModelProperty', 'ModelId', { cascade_delete => 1 });
__PACKAGE__->has_many(ModelRelations => 'Schema::Result::ModelRelation', 'PrincipalId', { cascade_delete => 1 });

# 创建模型
sub Create {
    my ($class, $schema,  $param) = @_;

    my $aggregateId = $param->{AggregateId};
    my $modelVo = $param->{ModelVo};
    my $modelIdentityId = $param->{ModelIdentityId};

    # 创建新的模型
    my $newModel = $schema->resultset('Model')->create(
        {
            AggregateId => $aggregateId,
            IdentityId => $modelIdentityId,
            IsAggregate => $modelVo->{IsAggregate},
            Name => $modelVo->{Name},
            Comment => $modelVo->{Comment},
        }
    );

    # 创建模型属性
    foreach my $propertyVo (@{$modelVo->{PropertyVos}}){
        my $newProperty = Schema::Result::ModelProperty->Create(
            $schema,
            {
                ModelId => $newModel->Id,
                PropertyVo => $propertyVo,
            }
        );
    }

    return $newModel;

}

# 删除
sub Delete {
    my ($self) = @_;

    $self->delete;
}

1;
